<script setup>
import { ref } from 'vue'
import { getAllRoleAPI, addOrUpdateRoleAPI, getAllMenuListAPI, setPermissionAPI, removeRoleAPI } from '@/api/acl/role'
import { useLayoutSettingStore } from '@/store/modules/setting'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'

const settingStore = useLayoutSettingStore()

const currentPage = ref(1)

const pageSize = ref(3)

// 搜索职位关键字
const keyword = ref('')

// 存储全部已有的职位
const allRole = ref([])

// 总数
const total = ref(0)

// 收集新增岗位数据
const roleParams = ref({
  roleName: ''
})

// 表单对象
const form = ref()

// 获取全部角色
const getAllRole = async (pager = 1) => {
  currentPage.value = pager
  let res = await getAllRoleAPI(currentPage.value, pageSize.value, keyword.value)
  if(res.code === 200) {
    allRole.value = res.data.records
    total.value = res.data.total
  }
}

getAllRole()

const handlerSizeChange = () => {
  getAllRole()
}

const search = () => {
  getAllRole()
  keyword.value = ''
}

const reset = () => {
  settingStore.refresh = !settingStore.refresh
}

// 控制对话框显示隐藏
const dialogVisible = ref(false)

// 添加职位按钮回调
const addRole = () => {
  dialogVisible.value = true
  // 清空数据
  Object.assign(roleParams.value, {
    roleName: '',
    id: 0
  })
  // 清空上一次校验规则错误结果
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}

// 修改职位按钮回调
const updateRole = (row) => {
  dialogVisible.value = true
  // 存储已有的职位信息
  Object.assign(roleParams.value, row)
  // 清空上一次校验规则错误结果
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}

// 取消按钮的回调
const cancel = () => {
  dialogVisible.value = false
}



// 校验职位名
const checkRoleName = (rule, value, callback) => {
  if(value.trim().length >= 2) {
    callback()
  } else {
    callback('职位名称至少两位')
  }
}

// 职位的校验规则
const rules = {
  roleName: [
    {required: true, trigger: 'blur', validator: checkRoleName}
  ]
}

// 保存按钮的回调
const save = async () => {
  await form.value.validate()
  let res = await addOrUpdateRoleAPI(roleParams.value)
  if(res.code === 200) {
    ElMessage({
      type: 'success',
      message: roleParams.value.id ? '更新成功' : '添加成功'
    })
    dialogVisible.value = false
    // 再次获取全部的职位
    getAllRole(roleParams.value.id ? currentPage.value : 1)
  }
}

// 控制抽屉组件显隐
const drawer = ref(false)

// 定义数组存储用户权限数据
const menuArr = ref([])

// 准备一个数组用于存储选中的id
const selectArr = ref([])

// 获取树形控件实例
const tree = ref()

// 分配权限按钮的回调
const setPermission = async (row) => {
  drawer.value = true
  // 收集当前要分类的职位的数据
  Object.assign(roleParams.value, row)
  // 根据职位获取权限数据
  let res = await getAllMenuListAPI(roleParams.value.id)
  if(res.code === 200) {
    menuArr.value = res.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}

function filterSelectArr(allArr, select) {
  allArr.forEach(item => {
    if (item.select && item.level === 4) {
      select.push(item.id)
    }
    if(item.children && item.children.length > 0) {
      filterSelectArr(item.children, select)
    }
  })
  return select
}

const defaultProps = {
  children: 'children',
  label: 'name',
}

// 分配权限保存按钮的回调
const handler = async () => {
  // 职位id
  const roleId = roleParams.value.id
  // 选中节点的id
  const arr = tree.value.getCheckedKeys()
  // 半选的id
  const arr1 = tree.value.getHalfCheckedKeys()
  const permissionId = arr.concat(arr1)
  let res = await setPermissionAPI(roleId, permissionId)
  if(res.code === 200) {
    // 关闭抽屉
    drawer.value = false
    // 提示信息
    ElMessage({
      type: 'success',
      message: '分配权限成功'
    })
    // 刷新页面，防止更改了自己账号的权限，可以看到直观影响
    window.location.reload()
  }
}

// 删除角色
const removeRole = async (roleId) => {
  let res = await removeRoleAPI(roleId)
  console.log(res)
  if(res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getAllRole(allRole.value.length > 1 ? currentPage.value : currentPage.value - 1)
  }
}
</script>

<template>
  <div>
    <el-card style="height: 80px;">
      <el-form class="form">
        <el-form-item label="职位搜索">
          <el-input placeholder="请输入搜索职位关键字" v-model="keyword" clearable /> 
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" :disabled="!keyword" @click="search">搜索</el-button>
          <el-button type="primary" size="default" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0;">
      <el-button type="primary" size="default" icon="Plus" @click="addRole">添加职位</el-button>
      <el-table border style="margin: 10px 0;" :data="allRole">
        <el-table-column label="#" type="index" align="center" width="80"></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column label="职位名称" align="center" show-overflow-tooltip prop="roleName"></el-table-column>
        <el-table-column label="创建时间" align="center" show-overflow-tooltip prop="createTime"></el-table-column>
        <el-table-column label="更新时间" align="center" show-overflow-tooltip prop="updateTime"></el-table-column>
        <el-table-column label="操作" align="center" width="360">
          <template #default="{row}">
            <el-button type="primary" size="default" icon="User" @click="setPermission(row)">分配角色</el-button>
            <el-button type="primary" size="default" icon="Edit" @click="updateRole(row)">编辑</el-button>
            <el-popconfirm
            :title="`你确定要删除${row.roleName}吗？`"
            @confirm="removeRole(row.id)"
            width="200">
              <template #reference><el-button type="primary" size="default" icon="Delete">删除</el-button></template>
            </el-popconfirm>
            
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
      v-model:currentPage="currentPage"
      :page-sizes="[1, 2, 3, 4]"
      v-model:page-size="pageSize"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      background
      @current-change="getAllRole"
      @size-change="handlerSizeChange">
      </el-pagination>
      
    </el-card>
    <!-- 对话框： 添加与更新已有职位 -->
    <el-dialog v-model="dialogVisible" :title="roleParams.id ? '修改职位' : '添加职位'" :align-center="true">
      <el-form style="padding: 40px;" :model="roleParams" ref="form" :rules="rules">
        <el-form-item label="职位名称" prop="roleName">
          <el-input v-model="roleParams.roleName" placeholder="请输入职位名称"  clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="save">确认</el-button>
      </template>
    </el-dialog>
    <!-- 抽屉:分配权限 -->
    <el-drawer title="分配权限" v-model="drawer" direction="rtl" size="30%">
      <template #default>
        <el-tree ref="tree" :data="menuArr" node-key="id" :props="defaultProps" :show-checkbox="true" :default-expanded-keys="[2, 3]" :default-checked-keys="selectArr"></el-tree>
        
      </template>
      <template #footer>
        <el-button type="primary" size="default" @click="drawer = false">取消</el-button>
        <el-button type="primary" size="default" @click="handler">保存</el-button>
        
      </template>
    </el-drawer>
    
  </div>
</template>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
